//
//  JZPageCategoryView.m
//  eStudy(comprehensive)
//
//  Created by 飞猪 on 2018/10/26.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JZPageCategoryView.h"
#import "JZPageControllerConfig.h"
#import "JZPageContentView.h"

@interface JZPageCategoryView () <UIScrollViewDelegate, JZPageContentViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIView *indicatorLine;

@property (nonatomic, strong) NSMutableArray<UILabel *> *categoryLabels;

#pragma mark - 记录
@property (nonatomic, strong) NSArray<NSString *> *titles;
@property (nonatomic) NSInteger selectedIndex;
@property (nonatomic, strong) JZPageControllerConfig *config;
@property (nonatomic, strong) UILabel *selectedLab;

@end

@implementation JZPageCategoryView

#pragma mark - LifeCycle
- (instancetype)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame config:[JZPageControllerConfig new] titles:@[] selectedIndex:0];
}
//
//- (instancetype)initWithCoder:(NSCoder *)coder {
//    self = [super initWithCoder:coder];
//    if (self) {
//        [self createViews];
//    }
//    return self;
//}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self layoutSubview];
}

#pragma mark - APIs
- (instancetype)initWithFrame:(CGRect)frame
                       config:(JZPageControllerConfig *)config
                       titles:(NSArray<NSString *> *)titles
                selectedIndex:(NSInteger)selectedIndex {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.titles = titles;
        self.selectedIndex = selectedIndex;
        self.config = config;
        
        [self createViews];
    }
    return self;
}

#pragma mark - CreateViews
- (void)createViews {
    self.backgroundColor = [UIColor whiteColor];
    self.selectedIndex = self.config.selectedIndex;
    
    // 0.
    [self addSubview:self.scrollView];
    
    // 1.
    for (NSInteger index = 0; index < self.titles.count; ++index) {
        UILabel *lab = [[UILabel alloc] init];
        lab.tag = index;
        lab.text = [self.titles objectAtIndex:index];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.textColor = index == self.selectedIndex ? self.config.titleSelectedColor : self.config.titleColor;
        lab.font = index == self.selectedIndex ? self.config.titleSelectedFont : self.config.titleFont;
        if (index == self.selectedIndex) {
            self.selectedLab = lab;
        }
        
        [self.scrollView addSubview:lab];
        [self.categoryLabels addObject:lab];
        
        lab.userInteractionEnabled = YES;
        [lab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labTap:)]];
    }
    
    // 2.
    [self.scrollView addSubview:self.indicatorLine];

}

- (void)layoutSubview {
    
    self.scrollView.frame = CGRectMake((self.bounds.size.width - 207) * 0.5, 0, 207, self.bounds.size.height);
    
    if (self.config.categoryType == JZPageControllerCategoryTypeOther) {
        [self layoutSizeFitLabels];
    }
    else {
        [self layoutAverageLabels];
    }
    
    [self layoutIndicatorLine];
}

/**
 sizeThatFits:  会计算出最优的 size 但不会改变自己的 size
 sizeToFit:     会计算出最优的 size 而且会改变自己的 size
 */
- (void)layoutSizeFitLabels {
    
    CGFloat x = 0;
    CGFloat y = 0, h = self.scrollView.bounds.size.height, w = self.scrollView.bounds.size.width / self.categoryLabels.count;
    
    for (NSInteger index = 0; index < self.titles.count; ++index) {
        UILabel *lab = self.categoryLabels[index];
        CGRect labF = lab.frame;
        
        if (self.config.categoryViewScrollEnable) {
            if (index == 0) {
                x = self.config.titleMargin * 0.5;
            }
            labF.origin.x = x;
            labF.origin.y = y;
            labF.size.height = h;
            CGSize size = [lab sizeThatFits:CGSizeZero];
            labF.size.width = size.width + self.config.titleMargin;
            
            x += labF.size.width;
        }
        else {
            labF.origin.x = index * lab.frame.size.width;
            labF.origin.y = y;
            labF.size.width = w;
            labF.size.height = h;
        }
        
        lab.frame = labF;
    }
    
    if (self.config.categoryViewScrollEnable) {
        
        UILabel *lab = [self.categoryLabels lastObject];
        CGFloat w = CGRectGetMaxX(lab.frame) + self.config.titleMargin * 0.5;
        self.scrollView.contentSize = CGSizeMake(w, self.scrollView.contentSize.height);
    }
    
}

- (void)layoutAverageLabels {
    
    CGFloat y = 0, h = self.scrollView.bounds.size.height, w = self.scrollView.bounds.size.width / self.categoryLabels.count;
    CGFloat x = w;
    
    for (NSInteger index = 0; index < self.titles.count; ++index) {
        UILabel *lab = self.categoryLabels[index];
        lab.frame = CGRectMake(x * index, y, w, h);
    }
    
    self.scrollView.scrollEnabled = NO;
    
}

- (void)layoutIndicatorLine {
    
    UILabel *lab = self.categoryLabels[self.selectedIndex];
    CGFloat x = lab.frame.origin.x + (lab.frame.size.width - self.config.indicatorLineWidth) * 0.5;
    CGFloat y = self.bounds.size.height - self.config.indicatorLineHeight;
    CGFloat w = self.config.indicatorLineWidth;
    CGFloat h = self.config.indicatorLineHeight;
    
    self.indicatorLine.frame = CGRectMake(x, y, w, h);
    
}

#pragma mark - Event
- (void)labTap:(UITapGestureRecognizer *)ges {
    
    NSInteger index = ges.view.tag;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageCategoryView:clickedAtIndex:)]) {
        [self.delegate pageCategoryView:self clickedAtIndex:index];
    }
    
    [self tapLabel:index];
}

- (void)tapLabel:(NSInteger)index {
    
    [self changeLabelStyleatIndex:index];
    [self changeIndicator:index];
    [self scrollTo:index];
    
}

- (void)changeLabelStyleatIndex:(NSInteger)atIndex {
    
    // 切换颜色和字体
    UILabel *lab = self.categoryLabels[atIndex];
    
    if (self.selectedLab) {
        UILabel *selectedLabel = self.selectedLab;
        if (selectedLabel != lab) {
            
            selectedLabel.textColor = self.config.titleColor;
            selectedLabel.font = self.config.titleFont;
            
            lab.textColor = self.config.titleSelectedColor;
            lab.font = self.config.titleSelectedFont;
            
            self.selectedLab = lab;
        }
    }
    else {
        lab.textColor = self.config.titleSelectedColor;
        lab.font = self.config.titleSelectedFont;
        
        self.selectedLab = lab;
    }
    
    
}

- (void)changeIndicator:(NSInteger)toIndex {
    
    UILabel *lab = self.categoryLabels[toIndex];
    
    [UIView animateWithDuration:0.1 delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect rect = self.indicatorLine.frame;
        rect.origin.x = CGRectGetMinX(lab.frame) + (lab.frame.size.width - rect.size.width) * 0.5;
        self.indicatorLine.frame = rect;
    } completion:nil];
    
}

- (void)scrollTo:(NSInteger)index {
    
    UILabel *lab = self.categoryLabels[index];
    
    CGRect rect =  [self convertRect:lab.frame fromView:self.scrollView];
    
    if (index == 0 || index == self.categoryLabels.count - 1) {
        
        if (CGRectGetMinX(rect) < 0) {
            
            CGPoint point = CGPointMake(0, self.scrollView.contentOffset.y);
            [self.scrollView setContentOffset:point animated:YES];
            
            return;
        }
        
        if (CGRectGetMaxX(rect) > self.bounds.size.width) {
            
            CGFloat margin = CGRectGetMaxX(rect) - self.bounds.size.width;
            CGFloat x = self.scrollView.contentOffset.x + margin;
            CGPoint point = CGPointMake(x, self.scrollView.contentOffset.y);
            [self.scrollView setContentOffset:point animated:YES];
        }
        
        return;
    }
    
    
    UILabel *prelab = self.categoryLabels[index - 1];
    
    UILabel *nextlab = self.categoryLabels[index + 1];
    
    
    if (((CGRectGetMinX(rect) < prelab.frame.size.width) && CGRectGetMinX(rect) >= 0) || (CGRectGetMinX(rect) < 0)) {
        CGFloat leftMargin = prelab.frame.size.width - CGRectGetMinX(rect);
        CGFloat x = self.scrollView.contentOffset.x - leftMargin;
        CGPoint point = CGPointMake(x, self.scrollView.contentOffset.y);
        [self.scrollView setContentOffset:point animated:YES];
        return;
    }
    
    CGFloat rightMargin = self.bounds.size.width - CGRectGetMaxX(rect);
    if ((rightMargin < nextlab.frame.size.width && rightMargin >= 0) || (rightMargin < 0)) {
        CGFloat margin = nextlab.frame.size.width - rightMargin;
        CGFloat x = self.scrollView.contentOffset.x + margin;
        CGPoint point = CGPointMake(x, self.scrollView.contentOffset.y);
        [self.scrollView setContentOffset:point animated:YES];
    }
    
    
}

#pragma mark - Lazyload

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.backgroundColor = [UIColor whiteColor];
        scrollView.delegate = self;
        if (@available(iOS 11.0, *)) {
          scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        _scrollView = scrollView;
    }
    return _scrollView;
}

- (UIView *)indicatorLine {
    if (!_indicatorLine) {
        
        UIView *line = [[UIView alloc] init];
        line.hidden = !self.config.showIndicatorLine;
        line.backgroundColor = self.config.indicatorLineColor;
        
        _indicatorLine = line;
    }
    return _indicatorLine;
}

- (NSMutableArray<UILabel *> *)categoryLabels {
    if (!_categoryLabels) {
        _categoryLabels = [NSMutableArray array];
    }
    return _categoryLabels;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - JZPageContentViewDelegate
- (void)pageContentView:(JZPageContentView *)pageContentView scrolledToIndex:(NSInteger)index {
    
    [self tapLabel:index];

}

@end
